//
//  DiamondBuyViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/2.
//

import UIKit

class DiamondBuyViewController: BaseViewController {
    let headerViwe = DiamondBuyHeaderView()
    var dataSource:[ProductModel] = []
    let disposeBag = DisposeBag()
    var service:SubscribeService?

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: DiamondBuyGoodsCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        
        return tableView
    }()
    
    private lazy var buyBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "立即支付"
        button.titleColorForNormal = Theme.color.text_d1
        button.titleFont = UIFont.pingFangSCMedium(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#45FFFF")
        button.allRound(23)
        return button
    }()
    private lazy var footerView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var tipsLb: UILabel = {
        let label = UILabel()
        label.font = UIFont.pingFangSCRegular(ofSize: 14)
        label.textColor = UIColor(hexString: "#FFFFFF", transparency: 0.7)
        label.numberOfLines = 0
        label.text = ""
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#28272D")
        self.navigationItem.title = "充值中心"
        self.view.addSubview(tableView)
        self.view.addSubview(buyBtn)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        
        self.buyBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.trailing.equalToSuperview().inset(24)
            make.height.equalTo(46)
        }
        
        self.tableView.tableHeaderView = self.headerViwe
        self.footerView.addSubview(tipsLb)
        tipsLb.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
        }
       
        let rightBtn = UIButton(type: .custom)
        rightBtn.setImage(UIImage(named: "icon_recharge"), for: .normal)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            let vc = RechargePageViewController()
            self?.navigationController?.pushViewController(vc)
        }
        requestGoods()
        getDesc()
        self.headerViwe.moneyLb.text = "\(Appearance.shared.accoutModel?.userOtherInfo?.score ?? 0)"
        GlobalRx.userInfoSubject.observe(on: MainScheduler.instance).subscribe(onNext: { model in
            self.headerViwe.moneyLb.text = "\(Appearance.shared.accoutModel?.userOtherInfo?.score ?? 0)"
        }).disposed(by: disposeBag)
        bindEvent()
        
        buyBtn.setClosureTouchUpInside_k { [weak self] in
            self?.clickSubscribe()
        }
    }
    
    func bindEvent(){
        self.service = SubscribeService.shared
        self.service?.PaySuccessBlock = { orderId in
            NDProgressHUD.showSuccess(title: "", subtitle: "购买成功")
        }
        self.service?.payBlock = {[weak self] type, msg, code in
            XLog.d("支付回调 type", "\(type) \(msg)")
            guard let self = self else { return }
            if type == 0 {
                NDProgressHUD.show(message: msg)
            }else if type == -1 {
                if msg.count > 0 {
                    NDProgressHUD.showError(title: "", subtitle: msg)
                }
            }else if type == 1{
                NDProgressHUD.show(message: msg)
//                RequestService.instance.getUserInfo()
            }else if type == -2 {
                self.tableView.reloadData()
                NDProgressHUD.show(message: msg)
            }
        }
    }
    
    func requestGoods(){
        NDProgressHUD.showLoading()
        RequestService.instance.scoreProduct { models in
            NDProgressHUD.hide()
            self.dataSource = models
            self.tableView.reloadData()
        } failureClosure: { error in
            NDProgressHUD.hide()
        }
    }
    
    func reloadData(model:ProductModel){
        for i in 0..<self.dataSource.count {
            self.dataSource[i].isSelect = false
        }
        if let index = self.dataSource.firstIndex(where: { $0.id ?? 0 == model.id ?? 0}) {
            self.dataSource[index].isSelect = true
        }
        self.tableView.reloadData()
    }
    
    func getDesc(){
        RequestService.instance.videoDescs { [weak self] dict in
            guard let self = self else { return }
            self.tipsLb.text = dict["rules"] as? String ?? ""
            if let text = dict["rules"] as? String {
                let getHeight = text.height(withConstrainedWidth: SCREEN_WIDTH - 32, font: UIFont.pingFangSCRegular(ofSize: 14))
                
                self.footerView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: getHeight + 72)
                self.tableView.tableFooterView = self.footerView
            }
        }
    }
    
    func clickSubscribe(){
        if let model = self.dataSource.first(where: { $0.isSelect }) {
            NDProgressHUD.showLoading()
            let productIds = self.dataSource.compactMap { $0.apple_product_id ?? "" }
            self.service?.buyProducts(productId: model.apple_product_id ?? "", allProductIds: productIds)
        }
    }
}
extension DiamondBuyViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: DiamondBuyGoodsCell.self, for: indexPath)
        if !self.dataSource.isEmpty {
            cell.setup(models: self.dataSource)
            cell.chooseProduct = { [weak self] model in
                self?.reloadData(model: model)
            }
        }
         return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70 + (GET_WIDTH(W: 90) * (self.dataSource.count > 3 ? 2 : 1))
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        section == 2 ? 0.01 : 0.01
    }
}
